<?php
/**
 * Created by PhpStorm.
 * User: yutongfu
 * Date: 2019/7/6
 * Time: 9:42 AM
 */
include './CacheRedis.php';
class WebsocketTest
{
    public $server;

    public function __construct()
    {
        /**
         * 连接websocket服务器
         * 设置host，0.0.0.0代表任意ip都能访问
         * 设置端口 9501
         */
        $this->server = new Swoole\WebSocket\Server("0.0.0.0", 9501);
        //$request 是一个Http请求对象，包含了客户端发来的握手请求信息
        $this->server->on('open', function (swoole_websocket_server $server, $request) {
            //var_dump($server);
            echo "连接上了";
        });
        //处理接收到的数据，并推送到客户端
        $this->server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
            //todo 接收过来的数据，解析，根据条件，先缓存到数据库
            $redis = CacheRedis::getInstance();
            $redis->hset('MessagePush',$frame->fd,$frame->data);
            //todo 如果针对接收过来数据，解析，然后根据条件，存入数据库
            //$server->push($frame->fd, "服务端向客户端发送数据");
            foreach ($server->connections as $fd) {
                // 需要先判断是否是正确的websocket连接，否则有可能会push失败
                if ($server->isEstablished($fd)) {
                    $server->push($fd, $frame->data);
                }
            }

        });
        //关闭连接
        $this->server->on('close', function ($ser, $fd) {
            echo "client {$fd} closed\n";
        });
        $this->server->start();
    }
}

new WebsocketTest();